<?php
namespace Home\Controller;
use Think\Controller;
use Com\WechatAuth;
class ZhuceController extends Controller {

	 private static $appid = 'wx1b2480648763a8ef'; //AppID(应用ID)
     private static $token = 'ftaoweixin'; //微信后台填写的TOKEN
	 private static $secret='4b3303c981ffcd8023aff02ec7f0b27e';
    public function index(){
		//获取临时openid
		
		$openid=$_GET['code'];
		$_SESSION['openid']=$openid;
		
		$wechatauth=new WechatAuth(self::$appid,self::$secret);
		$at=$wechatauth->getAccessToken('code',$openid);//获取access_token
		$userInfo=$wechatauth->getUserInfo($openid);//获取用户信息
		$_SESSION['userInfo']=$userInfo;
		//dump($userInfo);
		$user=M('user');
		if($code=$user->where('openid="'.$userInfo['openid'].'"')->getField('usercode'))
		{
			$this->display('Warning');
			return;
		}
       
		
		$this->display();
	}
	public function register()
	{	
		$userInfo=$_SESSION['userInfo'];
		
		$openid=$userInfo['openid'];
		$nickname=$userInfo['nickname'];
		$sex=$userInfo['sex'];
		$language=$userInfo['language'];
		$city=$userInfo['city'];
		$province=$userInfo['province'];
		$country=$userInfo['country'];
		$headimgurl=$userInfo['headimgurl'];
		$phone=$_POST["phone"];
		$name=$_POST["name"];
		$class=$_POST["class"];
		$school=$_POST["school"];
		$usercode=$this->getRandStr(8);
		/*test!*/
		/*
		$openid=$_SESSION['openid'];
		$phone="31234572315";
		$password="password";
		*/
		
		
		if($phone!=""&&$name!=""&&$class!=""&&$school!="")
		{
			$user=M('user');
			try
			{
				//id为返回的uer表id值，暂时无用
				$id=$user->add(array('openid'=>$openid,'phone'=>$phone,'name'=>$name,'class'=>$class,'school'=>$school,'nickname'=>$nickname,
				'sex'=>$sex,'language'=>$language,'city'=>$city,'province'=>$province,'country'=>$country,
				'headimgurl'=>$headimgurl,'usercode'=>$usercode));
				//echo "注册成功！活动码是".$usercode;
				$this->display('Correct');
			}
			catch (\Exception $e)
			{
				//echo '手机或者微信号已注册过,或者活动码生成过的';
				$this->display('Error');
			}
		}
		else
		{
			$this->display('Error2');
		}
		
	}
	
	private function getRandStr($len)
	{
		$chars = array( 
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",  
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",  
        "w", "x", "y", "z", "0", "1", "2",  
        "3", "4", "5", "6", "7", "8", "9" 
		); 
		$charsLen = count($chars) - 1; 
		shuffle($chars);   
		$output = ""; 
		for ($i=0; $i<$len; $i++) 
		{ 
			$output .= $chars[mt_rand(0, $charsLen)]; 
		}  
			return $output;
	}
		
}